//
//  CollagePickerViewController.m
//  xiaoyuanshenghuoquan
//
//  Created by Fenrir on 13-11-15.
//  Copyright (c) 2013年 mypocketbaby.com. All rights reserved.
//

#import "CollagePickerViewController.h"
#import "Collage.h"
#import "pinyin.h"
#import "CollageManager.h"
#import "JSONRequest.h"
#import "JMFBase.h"

@interface CollagePickerViewController ()<JSONRequestDelegate>

@end

@implementation CollagePickerViewController
{
    NSMutableArray *_dataSource;
    NSMutableArray *_sectionForData;
    NSIndexPath *_selectedIndexPath;
}
@synthesize region = _region;
@synthesize delegate = _delegate;
@synthesize selectedCollageName = _selectedCollageName;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        
        _sectionForData = [NSMutableArray new];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.title = _L(@"vc_title_110");
    self.tableView.backgroundView = nil;
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIButton *confirmButton = [Helper buttonWithStyle:ButtonStyleNavigationComfirm];
    [confirmButton addTarget:self action:@selector(confirmButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:confirmButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    _dataSource = [CollageManager collagesWithRegion:_region];
//    NSLog(@"%@",_dataSource);
//    for (Collage *c in _dataSource) {
//        NSLog(@"%@",c.name);
//    }
    [self sectionInitData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件

- (void)backButtonEvent:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)confirmButtonEvent:(id)sender
{
    if (_selectedIndexPath == nil) {

        [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_137")];
        return;
    }
    
//    if ([_delegate respondsToSelector:@selector(collageDidSelected:)]) {
//        [_delegate collageDidSelected:(Collage *)_sectionForData[_selectedIndexPath.section][_selectedIndexPath.row]];
//    }

    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstTimeInXYSHQ"]) {
        Collage *collage = (Collage *)_sectionForData[_selectedIndexPath.section][_selectedIndexPath.row];
        
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_CHANGE_USERINFO];
        request.delegate = self;
        request.hudOn = true;
        request.hudTitle = _L(@"title_loading_01");
        [request setValue:[NSString stringWithFormat:@"%@ %@", collage.region,collage.name] forParameter:@"school"];
        request.requestMode = RequestModeMultiPart;
        [request asynchronous];
    }
    else {
        
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"fill_collage" object:(Collage *)_sectionForData[_selectedIndexPath.section][_selectedIndexPath.row]];
}

#pragma mark - 私有方法

- (void)sectionForData
{
    // 组装分区表初始默认数组
    // 循环将27个数组加入 分区数组(27个数组代表26个英文字母+1个＃号特殊字符)
    for (int i = 0; i < 27; i++) {
        [_sectionForData addObject:[NSMutableArray array]];
    }
    
    // 循环姓名数组
    for (Collage *collage in _dataSource) {
        // 得到当前元素姓名
        NSString *contactsName = [collage name];
        
        // 1、得到姓名0索引位置的字符
        // 2、调用pinyin类实例方法pinyinFirstLetter并传入字符，判断传入的字符是汉字还是英文，如果是汉字返回汉字所属的字母，不属于汉字返回传入字符
        // 3、将拼音方法传回的字符组装成字符串
        // 4、并转换成大写格式
        NSString *sectionPinYinLetter = nil;
        NSUInteger firstLetterLocation = NSNotFound;
        //长度检查，空名字不截取
        if (contactsName != nil && contactsName.length > 0) {
            sectionPinYinLetter = [[NSString stringWithFormat:@"%c",pinyinFirstLetter([contactsName characterAtIndex:0])] uppercaseString];
            firstLetterLocation = [ALPHA rangeOfString:[sectionPinYinLetter substringToIndex:1]].location;
        }
        
        // 1、截取sectionUgoName的第一个字符
        // 2、并判断此字符在26个英文字母+#号的位置，并赋值
        
        // 如果在26个之中的字母组成数组中有这个位置
        if (firstLetterLocation != NSNotFound) {
            // 找到ugo分区数组，在这个索引位置对应的数组，并加入同样属于索引i对应元素，及UgoContacts类的对象
            [[_sectionForData objectAtIndex:firstLetterLocation] addObject:collage];
        }
        // 否则不在26个英文字母之中，用ALPHA数组最后一个特殊#号位置数组统一加入管理
        else {
            [[_sectionForData objectAtIndex:[ALPHA length] - 1] addObject:collage];
        }
    }
    
//    return sections;
}

/*!
 @abstract 初始化分区数据(组装分区数组、姓名数组、根据abc...z  26个字母对应26个分区+1个特殊分区＃号，对应字母分区放入对应姓名字母开头实体)
 */
- (void) sectionInitData
{
    // 查看通讯簿是否存在数据
    if ([_dataSource count] > 0) {
        // 清除以前分区数据
        [_sectionForData removeAllObjects];
        
        // 获取新分区数据
        [self sectionForData];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 27;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [_sectionForData[section] count];
}

// 分区标题头(分区栏最上面出现对应abc...)
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    // 存在本地联系人数据
    if (_dataSource.count > 0) {
        // 如果当前分区对应数组中没有数据
        if ([[_sectionForData objectAtIndex:section] count] > 0) {
            // 返回26个英文字母+1个＃号特殊字符中,指定分区索引的一个字母
            // 截取字符串解析  (26个英文字母+1个＃号特殊字符,指定分区索引开始截取 ＝ 保留右边数据) (右边数据只截取到索引1处 ＝ 保留左边数据)
            NSString *headerTitleString = [NSString stringWithFormat:@"%@", [[ALPHA substringFromIndex:section] substringToIndex:1]];
            
            return headerTitleString;
        }
        else {
            return nil;
        }
    }
    
    return nil;
}

// 右侧A-Z
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    // 存在本地地址薄数据
    if (_sectionForData.count > 0) {
        NSMutableArray *indices = [NSMutableArray array];
        // 26个英文字母+1个＃号特殊字符
        for (int i = 0; i < 27; i++) {
            // 将首字母加入数组
            // 截取字符串解析  (26个英文字母中,指定分区索引开始截取 ＝ 保留右边数据) (右边数据只截取到索引1处 ＝ 保留左边数据)
            //            if ([_sectionForDataSource[i] count] > 0) {
            
            [indices addObject:[[ALPHA substringFromIndex:i] substringToIndex:1]];
            //            }
        }
        return indices;
    }
    
    // 查询表
	return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        UIImageView* checkImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 14, 14)];
        cell.accessoryView = checkImageView;
    }
    
    Collage *collage = (Collage *)_sectionForData[indexPath.section][indexPath.row];
    
    cell.textLabel.text = [collage name];
    cell.textLabel.font = _SYS_FONT_006;
    if ([_selectedCollageName isEqualToString:[collage name]]) {
        ((UIImageView *)cell.accessoryView).image = [UIImage imageNamed:@"com_icon_014"];
    }
    else {
        ((UIImageView *)cell.accessoryView).image = [UIImage imageNamed:@"com_icon_013"];
    }
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

 */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (_selectedIndexPath != nil) {
        
        Collage *selectedCollage = [[_sectionForData objectAtIndex:_selectedIndexPath.section] objectAtIndex:_selectedIndexPath.row];
        
        //更改collage属性，再去掉cell的标记
        selectedCollage.status = NO;
        
        UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:_selectedIndexPath];
        
        ((UIImageView *)selectedCell.accessoryView).image = [UIImage imageNamed:@"com_icon_013"];
    }
    
    Collage *selectingCollage = [[_sectionForData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    selectingCollage.status = YES;
    UITableViewCell *selectingCell = [tableView cellForRowAtIndexPath:indexPath];
    ((UIImageView *)selectingCell.accessoryView).image = [UIImage imageNamed:@"com_icon_014"];
    
    _selectedIndexPath = indexPath;
    
}


#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstTimeInXYSHQ"];
        [self.navigationController dismissModalViewControllerAnimated:YES];
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}
@end
